package ru.royalgatemagazine.app.json;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import ru.royalgatemagazine.app.Debug;
import ru.royalgatemagazine.app.http.HttpSimpleClient;
import ru.royalgatemagazine.app.show.main.MainEntity;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

public class JsonApiReader {
	private JsonApiReader(){}
	public static void getMagazineList(final Context context, final JsonApiReaderListener listener, final Handler h){
		Runnable r = new Runnable() {
			@Override
			public void run() {
				final HttpSimpleClient client = new HttpSimpleClient(context);
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("act", "getmagazineslist"));
				String content = client.getContent(nameValuePairs);
				if(!TextUtils.isEmpty(content)){
//					Debug.log("JsonApiReader:content:"+content);
					final List<MainEntity> list = new ArrayList<MainEntity>();
					try{
						JSONObject json = new JSONObject(content);
						JSONArray array = json.getJSONArray("magazine");
						for(int i=0;i<array.length();i++){
							JSONObject o = (JSONObject) array.get(i);
							MainEntity.Builder b = new MainEntity.Builder();
							b.image(o.getString("image"));
							b.text(o.getString("text"));
							b.title(o.getString("title"));
							b.mid(o.getInt("mid"));
							b.pages(o.getInt("pages"));
							MainEntity entity = b.build();
							list.add(entity);
							Debug.log(entity);
						}
					}
					catch(Exception e){
						h.post(new Runnable() {
							@Override
							public void run() {
								listener.onError(client.getErrorCode());
							}
						});
						return;
					}
					h.post(new Runnable() {
						@Override
						public void run() {
							listener.onMagazineListLoaded(list);
						}
					});
				}
				else{
					Debug.log("JsonApiReader:!TextUtils.isEmpty(content)");
					h.post(new Runnable() {
						@Override
						public void run() {
							listener.onError(client.getErrorCode());
						}
					});
				}
			}
		};
		Thread t = new Thread(r);
		t.start();
	}
	
	public static interface JsonApiReaderListener{
		public void onMagazineListLoaded(List<MainEntity> list);
		public void onError(int erorCode);
	}
}
